package top.lemna.generator;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.hutool.core.io.file.FileNameUtil;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * freemarker tool
 *
 * @author xuxueli 2018-05-02 19:56:00
 */
@Slf4j
@Component
public class FreemarkerUtil {

	@Autowired
	private Configuration configuration;

	/**
	 * 传入需要转义的字符串进行转义 20200503 zhengkai.blog.csdn.net
	 */
	public static String escapeString(String originStr) {
		return originStr.replaceAll("井", "\\#").replaceAll("￥", "\\$");
	}

	/**
	 * process Template Into String
	 *
	 * @param template
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String processTemplateIntoString(Template template, Object model)
			throws IOException, TemplateException {

		StringWriter result = new StringWriter();
		template.process(model, result);
		return result.toString();
	}

	/**
	 * process String
	 *
	 * @param templateName
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String processString(String templatePath, String templateName, Map<String, Object> params)
			throws IOException, TemplateException {
		Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

//		freemarkerConfig.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class, "/templates/code-generator"));
		freemarkerConfig.setDirectoryForTemplateLoading(new File(templatePath));
		freemarkerConfig.setNumberFormat("#");
		freemarkerConfig.setClassicCompatible(true);
		freemarkerConfig.setDefaultEncoding("UTF-8");
		freemarkerConfig.setLocale(Locale.CHINA);
		freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

		Template template = freemarkerConfig.getTemplate(templateName);
		String htmlText = escapeString(processTemplateIntoString(template, params));
		return htmlText;
	}

}
